package com.example.x1c.networktest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 使用OKhttp重新实现
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = findViewById(R.id.send_request);
        responseText = findViewById(R.id.response_text);
        sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ");
                if(v.getId() == R.id.send_request){
                    //sendRequestWithHttpURLConnection();

                    // 使用OkHttp显示
                    // sendRequestWithOkHttp();

                    // 使用本机IP
                    // sendRequestWithOkHttp("http://192.168.31.224/get_data.xml");
                    sendRequestWithOkHttp("http://192.168.31.224/get_data.json");
                }

            }
        });
    }

    private void sendRequestWithHttpURLConnection(){
        Log.d(TAG, "sendRequestWithHttpURLConnection: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = reader.readLine())!=null){
                        Log.d(TAG, "run: " + line);
                        response.append(line);
                    }

                    // 显示文本
                    showResponse(response.toString());

                } catch (Exception e){
                    e.printStackTrace();
                } finally {
                    if(reader != null){
                        try{
                            reader.close();
                        }catch(IOException e){
                            e.printStackTrace();
                        }
                    }

                    if (connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "showResponse:  " +response);
                // 在这里进行UI操作，将结果显示到界面上
           responseText.setText(response);
            }
        });
    }

    private void sendRequestWithOkHttp(){
        Log.d(TAG, "sendRequestWithOkHttp: 用OkHttp显示");
        new Thread(new Runnable() {

            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();

                    Request request = new Request.Builder().url("http://www.baidu.com").
                                                            build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch(Exception e){
                    e.printStackTrace();
                }


            }
        }).start();
    }

    private void sendRequestWithOkHttp(final String url){
        Log.d(TAG, "sendRequestWithOkHttp: 用OkHttp显示");
        new Thread(new Runnable() {

            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();

                    Request request = new Request.Builder().url(url).
                            build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "run: " + responseData);

                    // 使用XMLPull
                    // showResponse(responseData);
                    // parseXMLWithPull(responseData);

                    // 使用sax
                    // parseXMLWithSAX(responseData);

                    // JSON
                    parseJSONWithJSONObject(responseData);

                    // JSON GSON
                    parseJSONWithGSON(responseData);

                } catch(Exception e){
                    e.printStackTrace();
                }


            }
        }).start();
    }

    /**
     * 使用pull解析XML
     * @param xmlData
     */
    private void parseXMLWithPull(String xmlData){
        try{
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while( eventType != XmlPullParser.END_DOCUMENT){
                String nodeName = xmlPullParser.getName();
                switch (eventType){
                    case XmlPullParser.START_TAG:{
                        if("id".equals(nodeName)){
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)){
                            name = xmlPullParser.nextText();
                        }else if("version".equals(nodeName)){
                            version = xmlPullParser.nextText();
                        }
                        break;
                    }

                    case XmlPullParser.END_TAG:{
                        if("app".equals(nodeName)){
                            Log.d(TAG, "parseXMLWithPull: id is " + id);
                            Log.d(TAG, "parseXMLWithPull: name is " + name);
                            Log.d(TAG, "parseXMLWithPull: version is " + version);
                        }
                    }
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }

        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 自定义handler
     * @param xmlData
     */
    private void parseXMLWithSAX(String xmlData){
        try{
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();

            // 将ContentHandler的实例设置到XMLReader中
            xmlReader.setContentHandler(handler);

            // 开始执行解析
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private void parseJSONWithJSONObject(String jsonData){
        try{
            JSONArray jsonArray = new JSONArray(jsonData);
            for(int i=0; i<jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d(TAG, "parseJSONWithJSONObject: id is " + id);
                Log.d(TAG, "parseJSONWithJSONObject: name is " + name);
                Log.d(TAG, "parseJSONWithJSONObject: version is " + version);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void parseJSONWithGSON(String jsonData){
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType());
        for (App app: appList
             ) {
            Log.d(TAG, "parseJSONWithGSON: " + app);

        }

    }

    private void testSend(){
        HttpUtil.sendHttpRequest("http://www.baidu.com", new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

            }

            @Override
            public void onError(Exception e) {

            }
        });
    }
}
